#!/bin/bash

for var in "$@"
do
    if [[ "$var" =~ ^"--multiverseid="([0-9]+)$ ]] || [[ "$var" =~ ^"--m="([0-9]+)$ ]] ; then
        multiverseid=${BASH_REMATCH[1]}
    elif [[ "$var" =~ ^"--outputdir="(.*)$ ]] || [[ "$var" =~ ^"--o="(.*)$ ]] ; then
        if [ ! -d "${BASH_REMATCH[1]}" ]; then
            echo "${BASH_REMATCH[1]} is not a directory";
            exit 1
        else
            outputDir="${BASH_REMATCH[1]}"
        fi
    elif [[ "$var" =~ ^"--outputname="(.*)$ ]] || [[ "$var" =~ ^"--n="(.*)$ ]] ; then
        outputName="${BASH_REMATCH[1]}"
    else
        echo "unknown argument $var"
        echo "Usage: bash getData.sh --multiverseid=<number>"
        exit 1
    fi
done

if [[ -z $multiverseid ]] ; then
    echo "Error: multiverseid not set"
    exit 1
elif [[ -z $outputDir ]] ; then
    echo "Error: outputdir not set"
    exit 1
fi

if [[ -z $outputName ]] ; then
    outputName="$multiverseid.jpg";
fi

echo "Storing image $outputDir/$outputName" > /dev/tty
wget -O "$outputDir/$outputName" "http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=$multiverseid&type=card" 1> /dev/null 2> /dev/null
